package com.smart.community.admin.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.community.admin.config.AliYunSmsConfigProperties;
import com.smart.community.admin.service.SmsService;
import com.smart.community.common.base.ex.ServiceException;
import com.smart.community.common.base.result.ResultStatus;
import com.smart.community.common.redis.dao.RedisDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author zhangwei
 */
@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    private RedisDao redisDao;

    @Resource
    private AsyncClient asyncClient;
    @Resource
    AliYunSmsConfigProperties properties;
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 发送验证码
     * <p>
     * 1. 生成验证吗
     * 2.  保存到redis中
     *
     * @param phone
     * @return
     */
    @Override
    public String sendSms(String phone) {
        String key = String.format("%s%s", REDIS_SMS_CODE_KEY_PREFIX, phone);
        try {
            if (!redisDao.hasKey(key)) {
                String code = RandomUtil.randomNumbers(6);
                redisDao.setEx(key, code, Duration.ofMinutes(1));
                Map<String, String> templateParam = new HashMap<>();
                templateParam.put(SMS_CODE_TEMPLATE_PARAM, code);
                SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                        //
                        .signName(properties.getSignName())
                        //
                        .templateCode(properties.getTemplateCode())
                        //
                        .phoneNumbers(phone)
                        //
                        .templateParam(objectMapper.writeValueAsString(templateParam)).build();
                CompletableFuture<SendSmsResponse> completableFuture = asyncClient.sendSms(sendSmsRequest);
                SendSmsResponse sendSmsResponse = completableFuture.get();
                String responseCode = sendSmsResponse.getBody().getCode();
                if (!SMS_RESPONSE_RESULT_OK.equals(responseCode)) {
                    throw new ServiceException(ResultStatus.SMS_SEND_VERIFY_CODE_ERROR);
                }
            }
        } catch (Exception ex) {
            throw new ServiceException(ResultStatus.SYS_ERROR);
        }
        return "success";
    }


}
